﻿var bm_prefix = "tg.bm:";
ADMIN_PAGE = "admin";
var fBrw = navigator.userAgent.indexOf("MSIE") != -1 && navigator.userAgent.indexOf("Windows") != -1;
var host = document.location.hostname;
if (host.indexOf("m.") < 0) {
    (function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=611631048879279";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
}

function getURLParameter(e, t) {
    return decodeURI((RegExp(t + "=" + "(.+?)(&|$)").exec(e) || [, null])[1])
}

function toggle(e) {
    jQuery(e).toggle()
}
function tabToggle(tabContentId) {
    jQuery('.tabcontent').hide();
    jQuery('.tab').removeClass('tabselected');
    var tabId = tabContentId.replace("tab", "");
    jQuery('#' + tabContentId).toggle();
    jQuery('#' + tabId).addClass('tabselected');
    location.hash = tabId;
}
function goto_link(e) {
    window.location = e
}

function open_link(e, t) {
    if (t == "false") {
        goto_link(e)
    } else {
        var n = window.open(e, "_blank");
        if (window.focus) {
            n.focus()
        }
    }
}

function createLink(e, t, n, r) {
    var i = "admin_" + e;
    if (t != null) {
        i += "_" + t + "_" + n
    }
    if (r != null) {
        i += "_" + r
    }
    return i + ".aspx"
}

function goPagingAjax(e, t) {
    ajaxRequest(e, t)
}

function ajaxRequest(e, t) {
    loading(true);
    var n = getURLParameter(e, "page");
    var r = 1;
    if (n) r = parseInt(n);
    loadGa(r);
    actionGaPush();
    jQuery.ajax({
        url: e,
        success: function (e) {
            loading(false);
            jQuery(t).html(e)
        },
        error: function () {
            loading(false)
        }
    })
}
function preLoad(params) {
    jQuery.ajax({ type: "POST", url: '/Ajax.aspx', data: params });
}
function ajaxBinding(e, t, n, r) {
    loading(true, t);
    jQuery.ajax({
        type: n ? n : "POST",
        url: "/Ajax.aspx",
        data: e,
        dataType: r ? r : "text",
        success: function (e) {
            loading(false, t);
            jQuery(t).html(e);
        },
        error: function () {
            loading(false, t);
        }
    })
}

function openEmail() {
    window.open(basepath + "SP/Email.aspx?u=" + window.location, null, "height=320,width=520,top=140,left=250,status=no,toolbar=no,menubar=no,location=no")
}

function closeEmail() {
    window.close();
    return true
}

function openPage(e, t, n) {
    window.open(e, null, "height=" + n + ",width=" + t + ",top=" + (screen.height - n) / 2 + ",left=" + (screen.width - t) / 2 + ",status=no,toolbar=no,menubar=no,location=no,scrollbars=yes")
}

function confirmDelete() {
    if (confirm("Bạn có chắc chắn xóa bản ghi này chứ?")) {
        return true
    }
    return false
}

function confirmRestore() {
    if (confirm("Bạn có chắc chắn lấy lại thông tin từ phiên bản này chứ?")) {
        return true
    }
    return false
}

function useAjax(e) {
    var t = {
        url: basepath + "Ajax.aspx",
        error: function (e, t, n) { },
        success: function (e) { }
    };
    if (typeof e != undefined) {
        jQuery.extend(t, e)
    }
    jQuery.ajax(t)
}

function isNumberKey(e) {
    var t = e.which ? e.which : event.keyCode;
    if (t > 31 && (t < 48 || t > 57)) return false;
    return true
}

function loading(e, t) {
    if (t) {
        if (e) {
            jQuery(t).prepend("<div id='targetloading'><img src='" + staticpath + "themes/images/ajax-loader.gif'/></div>")
        } else {
            jQuery("#targetloading").remove()
        }
    } else {
        if (e) {
            jQuery.msg({
                content: "<div id='targetloading' class='loading'><img src='" + staticpath + "themes/images/ajax-loader.gif'/></div>",
                autoUnblock: false,
                clickUnblock: false,
                fadeIn: 50,
                css: {
                    background: "transparent",
                    padding: "3px"
                }
            })
        } else {
            jQuery.msg("unblock", 50);
            jQuery("#targetloading").remove()
        }
    }
}

function resizeImgDetailContent() {
    var e = 200;
    $("img").each(function (t) {
        if ($(this).height() > $(this).width()) {
            var n = e;
            var r = Math.ceil($(this).width() / $(this).height() * e)
        } else {
            var r = e;
            var n = Math.ceil($(this).height() / $(this).width() * e)
        }
        $(this).css({
            height: n,
            width: r
        })
    })
}

function HtmlEncode(e) {
    if (!e) return "";
    var t = document.createElement("div");
    t.innerText = t.textContent = e;
    e = t.innerHTML;
    return e
}

function HtmlDecode(e) {
    if (!e) return "";
    var t = document.createElement("div");
    t.innerHTML = e;
    return t.firstChild.nodeValue
}

function isValidEmail(e) {
    if (e.length > 0) {
        var t = /^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$/;
        return t.test(e)
    }
    return false
}

function AdClick(e) {
    $.ajax({
        url: basepath + "Ajax.aspx",
        data: {
            p: "Banner",
            act: "clicked",
            id: e
        },
        dataType: "json",
        success: function (e) { }
    })
}

function resizeText(e, t) {
    var n = jQuery("#" + e);
    var r = n.css("font-size");
    var i = n.css("line-height");
    var s = parseInt(r.replace(/px/, "")) + parseInt(t);
    var o = parseInt(i.replace(/px/, "")) + parseInt(t);
    n.css("font-size", s + "px");
    n.css("line-height", o + "px");
    return false
}

function bookIncr(e, t) {
    jQuery.ajax({
        url: "/Ajax.aspx",
        type: "POST",
        data: { p: "Content", act: "incrview", bid: e, cid: t }
    })
}

function removeAllCookie() {
    jQuery.each(jQuery.cookie(), function (e, t) {
        jQuery.removeCookie(e)
    })
}

function getBookmarkKeys() {
    var e = "";
    jQuery.each(jQuery.cookie(), function (t, n) {
        if (t.indexOf(bm_prefix) >= 0) {
            e += t.replace(bm_prefix, "") + ","
        }
    });
    if (e.length > 0) e = e.substring(0, e.length - 1);
    return e
}

function autoBookmark(e) {
    var t = jQuery.cookie(bm_prefix + e);
    if (t) {
        var n = window.location.href;
        jQuery.cookie(bm_prefix + e, n, {
            expires: 7,
            path: "/"
        })
    }
}

function addBookmark(e) {
    var t = window.location.href;
    jQuery.cookie(bm_prefix + e, t, {
        expires: 7,
        path: "/"
    });
    alert("Đã thêm vào danh sách yêu thích");
    genBookmarkIcon(e)
}

function genBookmarkIcon(e) {
    var t = "<div class='follow hand' title='Đưa vào danh mục yêu thích' onclick='addBookmark(" + e + ");'></div>";
    var n = jQuery.cookie(bm_prefix + e);
    if (n) {
        t = "<div class='followed' title='Bạn đang theo dõi truyện này'></div>"
    }
    jQuery("#bmanchor").html(t)
}

function removeBookmark(e) {
    jQuery.removeCookie(bm_prefix + e)
}

function getBookmarkLastUrl(e) {
    var t = jQuery.cookie(bm_prefix + e);
    if (t) {
        window.location.href = t
    }
}

function loadBookmark() {
    var e = getBookmarkKeys();
    var t = jQuery("#bmcontent");
    if (e.length == 0) {
        t.html("");
        return
    }
    jQuery.ajax({
        url: basepath + "SP/BookMark.aspx",
        data: {
            ids: e
        },
        success: function (e) {
            t.html(e)
        }
    })
}

function resetTheme() {
    jQuery.removeCookie(cookiethemekey);
    jQuery("body").removeAttr("class");
    jQuery.ajax({
        url: "/Ajax.aspx",
        data: {
            p: "Themes",
            act: "reset"
        }
    })
}

function changeTheme(e) {
    jQuery.cookie(cookiethemekey, e, {
        expires: 7,
        path: "/"
    });
    jQuery("body").attr("class", e);
    jQuery.ajax({
        url: "/Ajax.aspx",
        data: {
            p: "Themes",
            act: "change",
            name: e
        }
    })
}

function loadTheme() {
    var e = jQuery.cookie(cookiethemekey);
    jQuery("body").attr("class", e)
}

function goChap(e, t) {
    if (!jQuery.isNumeric(t) || t < 0) {
        return
    };
    loading(true);
    jQuery.ajax({
        url: "/Ajax.aspx",
        data: {
            p: "Content",
            act: "gochap",
            bid: e,
            chap: t
        },
        dataType: "json",
        success: function (e) {
            loading(false);
            if (e.msg) {
                window.location.href = e.msg
            } else {
                alert("Không có chương này!");
            }
        },
        error: function () {
            alert("Lỗi tải trang!");
            loading(false)
        }
    })
}
function preloadChap(e, t) {
    if (!jQuery.isNumeric(t) || t < 0) {
        return;
    }
    actionGaPush();
    jQuery.ajax({
        url: "/Ajax.aspx",
        data: {
            p: "Content",
            act: "gochap",
            bid: e,
            chap: t
        }
    });
}
function goPageBook(e, t, n) {
    var r = "/services/bookchaps.aspx?bid=" + e;
    if (t > 1) {
        r += "&page=" + t
    }
    ajaxRequest(r, n)
}

function goPageBookAdmin(e, t, n) {
    var r = "/services/bookchapsadmin.aspx?bid=" + e;
    if (t > 1) {
        r += "&page=" + t
    }
    ajaxRequest(r, n)
}
function loadGa(e) {
    var t = window.location.href;
    var n = t.lastIndexOf("/");
    if (n > 0) t = t.substring(0, n + 1);
    n = t.indexOf("/page-");
    if (n > 0) t = t.substring(0, n + 1);
    var r = jQuery("title").html();
    n = r.indexOf("|Trang");
    if (n > 0) r = r.substring(0, n);
    if (e > 1) {
        r += "|Trang " + e;
        t += "page-" + e + "/"
    }
    jQuery("title").html(r);
    history.pushState(null, r, t);
    //    if (typeof _gaq !== "undefined") {
    //        _gaq.push(["_trackPageview", t]);
    //        _gaq.push(["b._trackPageview", t]);
    //        _gaq.push(["c._trackPageview", t]);
    //    }
}

function reportBook(id, msg) {
    preLoad({ p: "Book", act: "report", id: id, isbook: "1", msg: msg });
}
function reportContent(id, msg) {
    preLoad({ p: "Book", act: "report", id: id, isbook: "0", msg: msg });
}
function onChapEdit(id) {
    window.open('/Admin_Content_content_lists_edit.aspx?id=' + id, '_blank');
}
function onBookEdit(id) {
    window.open('/Admin_Book_Book_list_edit.aspx?id=' + id, '_blank');
}

function accountLogout() {
    $.ajax({
        type: "POST",
        url: "/Ajax.aspx",
        data: { p: 'Account', act: 'logout' },
        success: function (data) {
            $('#accountloginblock').html(data);
        }
    });
}

function openFeedburner() {
    var width = 550;
    var height = 520;
    var features, top, left;
    left = (window.screen.width - width) / 2;
    top = (window.screen.height - height) / 2;
    features = "width=" + width + ",height=" + height + ",top=" + top + ",left=" + left;
    void (window.open('http://feedburner.google.com/fb/a/mailverify?uri=truyengi&loc=en_US', 'Feedburner', features));
}
function getViewport() {
    var viewPortWidth;
    var viewPortHeight;

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    if (typeof window.innerWidth != 'undefined') {
        viewPortWidth = window.innerWidth,
        viewPortHeight = window.innerHeight
    }

        // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    else if (typeof document.documentElement != 'undefined'
    && typeof document.documentElement.clientWidth !=
    'undefined' && document.documentElement.clientWidth != 0) {
        viewPortWidth = document.documentElement.clientWidth,
		viewPortHeight = document.documentElement.clientHeight
    }

        // older versions of IE
    else {
        viewPortWidth = document.getElementsByTagName('body')[0].clientWidth,
        viewPortHeight = document.getElementsByTagName('body')[0].clientHeight
    }
    return [viewPortWidth, viewPortHeight];
}

function getXmlHttpObject() {
    var objXMLHttp = null;
    if (window.XMLHttpRequest) {
        objXMLHttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return objXMLHttp;
}
function actionGaPush() {
    ajaxAction("/services/datagaif.html");
}
function ajaxAction(url) {
    var xmlHttp = new getXmlHttpObject();
    if (xmlHttp == null) {
        return;
    }
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == 200) {
            document.getElementById('hidden_content').innerHTML = xmlHttp.responseText;
        }
    };
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

var cookiethemekey = "currentthemes";
jQuery(function ($) {
    $("form").bind("keypress", function (e) {
        if (e.keyCode == 13) return false
    });
	/*
	$(document).mouseup(function (e) {
        var container = $("#navlist");
        if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            container.hide();
        }
    });
	*/
});

(function ($) {
    $.sticky = function (stickyElement, $stopElement, stickyPos) {

        // To avoid scope issues, use 'base' instead of 'this' to reference this
        // class from internal events and functions.
        var base = this;

        var $stickyElement = $(stickyElement);
        var padding = 10;
        var isStuck = false;
        var originalLayout;

        function GetOriginalLayout() {
            if ($stickyElement) {

                var position = $stickyElement.offset();

                var original = new Object();
                original.isStickyRequired = stickyPos === "top";
                original.top = position.top;
                original.left = position.left;
                original.position = $stickyElement.css('position');

                // if one of the coords is negative return null to identify that we can't sticky
                if (original.top === -1)
                    return null;

                return original;
            }
        };

        function ResetLayout() {
            if (originalLayout) {
                $stickyElement.css('position', originalLayout.position);
                $stickyElement.css('top', originalLayout.top);
                $stickyElement.css('left', originalLayout.left);

                isStuck = false;
            }
        }

        base.ReGetOriginalLayout = function () {
            if (originalLayout) {

                // Position the element back normally
                ResetLayout();

                // recreate the settings to account for possible absolute position changes
                originalLayout = GetOriginalLayout();

                // apply new settings
                base.RepositionStickyElement();
            }
        };

        base.RepositionStickyElement = function () {

            var stopBounds;
            if ($stopElement && $stopElement.length)
                stopBounds = getBoundingRect($stopElement);

            var scrollTop = $(window).scrollTop();
            var stickyBounds = getBoundingRect($stickyElement);

            var stickTop;
            if (stopBounds && stickyBounds.bottom > stopBounds.top)
                stickTop = stickyBounds.top - (stickyBounds.bottom - stopBounds.top) - scrollTop;
            else if (scrollTop + padding >= originalLayout.top)
                stickTop = padding;
            else if (!isStuck)
                originalLayout = GetOriginalLayout();

            // If the element had previously hit a stop element then it would have been positioned
            // such that it wasn't overlapping the stop element. If we're now thinking we can set it
            // back to the top of the frame then we need to double-check
            if (stopBounds && (scrollTop + stickTop + stickyBounds.height) > stopBounds.top)
                stickTop = stickyBounds.top - (stickyBounds.bottom - stopBounds.top) - scrollTop;

            if (stickTop) {

                // base.ReGetOriginalLayout(true);

                $stickyElement.css('position', 'fixed');
                $stickyElement.css('top', stickTop);
                $stickyElement.css('left', originalLayout.left - $(window).scrollLeft());

                isStuck = true;

                /* REVIEW: [Yuriy] (CM 8Aug14) No idea how this is means to work. Doesn't make sense...
				// avoid flicker of content outside of div by forcing the div to take the size of
				// the iframe
				if ($stickyElementheight() === 0)
					$stickyElement.height($stickyElement.height());
				if ($stickyElement.width() === 0)
					$stickyElement.width($stickyElement.width());
				*/
            }
            else
                ResetLayout();
        };

        function getBoundingRect($element) {
            var bounds = $element.offset();

            bounds.width = $element.outerWidth(true); // true = include margins in the value
            bounds.height = $element.outerHeight(true);

            bounds.right = bounds.left + bounds.width;
            bounds.bottom = bounds.top + bounds.height;

            // Not needed.
            // bounds.marginVertical   = (bounds.height - $element.outerHeight(false)) / 2;
            // bounds.marginHorizontal = (bounds.width  - $element.outerWidth(false))  / 2;

            return bounds;
        }

        base.init = function () {

            stickyPos = stickyPos || "top";

            if ($stickyElement) {
                originalLayout = GetOriginalLayout();

                $(window).bind('resize', base.ReGetOriginalLayout);
                $(window).bind('scroll', base.RepositionStickyElement);

                // Looks crappy. The content to be fixed slides underneath the newly fixed content
                /*
				if ('ontouchmove' in window)
					$(window).bind('touchmove', base.RepositionStickyElement);
				*/
            }
        }

        base.init();
    };

    // Returns enhanced elements that will fix to the top of the page when the
    // page is scrolled.
    $.fn.sticky = function ($stopElement, stickyPos) {
        return this.each(function () {
            (new $.sticky(this, $stopElement, stickyPos));
        });
    };

})(jQuery);